#include "usermodel.h"
#include "db.h"
#include <iostream>
#include <stdlib.h>
using namespace std;

// User表的增加方法
bool UserModel::insert(User &user)
{
    // 1.组装sql语句
    char sql[1024] = {0};
    string strAccount = generateAccount();
    if (strAccount == "") return false;
    user.setAccount(strAccount);
    sprintf(sql, "insert into qousers(nickname, password, account, state) values('%s', '%s', '%s', '%s')",
            user.getNickName().c_str(), user.getPassword().c_str(), user.getAccount().c_str(), user.getState().c_str());

    MySQL mysql;
    if (mysql.connect())
    {
        if (mysql.update(sql))
        {
            // 获取插入成功的用户数据生成的主键id
            user.setId(mysql_insert_id(mysql.getConnection()));
            return true;
        }
    }

    return false;
}

// 根据用户号码查询用户信息
User UserModel::query(string strAccount)
{
    // 1.组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "select * from qousers where account = %s", strAccount.c_str());

    MySQL mysql;
    if (mysql.connect())
    {
        MYSQL_RES *res = mysql.query(sql);
        if (res != nullptr)
        {
            MYSQL_ROW row = mysql_fetch_row(res);
            if (row != nullptr)
            {
                User user;
                user.setId(atoi(row[0]));
                user.setAccount(row[1]);
                user.setNickName(row[2]);
                user.setPassword(row[3]);
                user.setState(row[4]);
                mysql_free_result(res);
                return user;
            }
        }
    }

    return User();
}

// 更新用户的状态信息
bool UserModel::updateState(User user)
{
    // 1.组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "update qousers set state = '%s' where account = %s", user.getState().c_str(), user.getAccount().c_str());

    MySQL mysql;
    if (mysql.connect())
    {
        if (mysql.update(sql))
        {
            return true;
        }
    }
    return false;
}

// 重置用户的状态信息
void UserModel::resetState()
{
    // 1.组装sql语句
    char sql[1024] = "update user set state = 'offline' where state = 'online'";

    MySQL mysql;
    if (mysql.connect())
    {
        mysql.update(sql);
    }
}

int UserModel::allUserCount()
{
    char sql[1024] = "SELECT COUNT(*) FROM qousers";

    MySQL mysql;
    if (mysql.connect())
    {
        MYSQL_RES *res = mysql.query(sql);
        if (res != nullptr)
        {
            MYSQL_ROW row = mysql_fetch_row(res);
            if (row != nullptr)
            {
                return atoi(row[0]);
            }
        }
    }
    return -1;
}

//生成账号
string UserModel::generateAccount()
{
    //查询用户数量
    if (allUserCount() == 90000) return "";
    //随机生成一个10001 - 99999之间的账号
    srand(time(NULL));
    while (true) {
        int iAccount = rand() % (99999 - 10001 + 1) + 10001;
        User user = query(to_string(iAccount));
        if (user.getId() == -1) {
            return to_string(iAccount);
        }
    }
    return "";
}